public interface UserService { public void addUser(User user); public User getUser(int id); }
public class UserServiceImpl implements UserService { public void addUser(User user) { System.out.println("add user into database."); } public User getUser(int id) { User user = new User(); user.setId(id); System.out.println("getUser from database."); return user; } }
public class CGProxyTest { public static void main(String[] args){ // 被代理的对象 Object proxyedObject = new UserServiceImpl(); CGProxy cgProxy = new CGProxy(proxyedObject); UserService proxyObject = (UserService) cgProxy.getProxyObject(); proxyObject.getUser(1); proxyObject.addUser(new User()); } }
输出结果:
1 2 3 4 5 6
do sth before.... getUser from database. do sth after.... do sth before.... add user into database. do sth after....